package com.ehi.common.jersey.util;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.ehi.common.jersey.status.ErrorMessageWrapper;
import com.ehi.common.jersey.status.ResponseTypeCode;

public class ExceptionUtil {

    public static void parseResponseWhenCallServiceFail(Response response,
            String externalServiceName) {
        ErrorMessageWrapper wrapper = null;
        String message = externalServiceName;
        if (response.getStatus() == Response.Status.OK.getStatusCode())
            return;
        if (response.hasEntity()) {
            if (MediaType.APPLICATION_JSON_TYPE.equals(response.getMediaType())) {
                wrapper = response.readEntity(ErrorMessageWrapper.class);
                wrapper.setStatusCode(response.getStatus());
                //throw new InvokeServiceException(GsonUtil.bean2json(wrapper, ErrorMessageWrapper.class));
            } else {
                String responseMsg = response.readEntity(String.class);
                message = externalServiceName + " response " + response.getStatus() + " error, detail:" + responseMsg;
                wrapper = ErrorMessageWrapper.buildErrorMessage(ResponseTypeCode.SERVER_ERROR, message);
                //throw new InvokeServiceException(GsonUtil.bean2json(wrapper, ErrorMessageWrapper.class));
            }
        } else {
            message = "Unknown Exception when call " + message;
            response.close();
            //throw new InvokeServiceException(message);
        }
    }
}
